<template>
  <div class="order-detail-page">
    <div class="order-detail-container">
      <div class="header">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <h1>订单详情</h1>
      </div>
      
      <!-- 加载中状态 -->
      <van-loading v-if="loading" type="spinner" color="#1989fa" class="loading" />
      
      <!-- 订单详情内容 -->
      <div v-else class="content">
        <!-- 订单状态 -->
        <div class="order-status-card">
          <div class="status-icon" :class="getStatusClass(orderData?.status || 0)">
            <van-icon 
              :name="getStatusIcon(orderData?.status || 0)" 
              size="40" 
              :color="getStatusIconColor(orderData?.status || 0)" 
            />
          </div>
          <h2>{{ getStatusText(orderData) }}</h2>
          <p v-if="orderData?.status === 1" class="valid-time">
            请在30分钟内完成打酒，超时订单将自动取消
          </p>
        </div>
        
        <!-- 酒品信息 -->
        <div class="item-card">
          <div class="item-header">
            <img :src="orderData?.item?.image || orderData?.item_image || 'https://via.placeholder.com/300x300?text=图片'" alt="酒品图片" class="item-image" />
            <div class="item-info">
              <h3>{{ orderData?.item?.name || orderData?.item_name || '未知酒品' }}</h3>              
              <p class="item-description" ></p>
              <div class="price-quantity">
                <span class="price">¥{{ (orderData?.price || 0) }}/ml</span>
                <span class="quantity">x{{ (orderData?.num || 0) }}ml</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 订单信息 -->
        <div class="order-info-card">
          <h3>订单信息</h3>
          <div class="info-list">
            <div class="info-item">
              <span class="label">订单编号</span>
              <span class="value">{{ orderData?.order_no || orderData?.id || '未知编号' }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间</span>
              <span class="value">{{ orderData?.create_time ? formatDateTime(orderData.create_time * 1000) : orderData?.create_time_text || '未知时间' }}</span>
            </div>
            <div class="info-item">
              <span class="label">设备编号</span>
              <span class="value">{{ orderData?.device_id || '未知设备' }}</span>
            </div>
          </div>
        </div>
        
        <!-- 店铺信息 -->
        <div class="shop-info-card">
          <h3>店铺信息</h3>
          <div class="info-list">
            <div class="info-item">
              <span class="label">店铺名称</span>
              <span class="value">{{ orderData?.shop?.shop_name || orderData?.shop_name || '未知店铺' }}</span>
            </div>
            <div class="info-item">
              <span class="label">店铺地址</span>
              <span class="value">{{ orderData?.shop?.address || '未知地址' }}</span>
            </div>
          </div>
        </div>
        
        <!-- 价格信息 -->
        <div class="price-info-card">
          <h3>价格明细</h3>
          <div class="info-list">
            <div class="info-item">
              <span class="label">商品金额</span>
              <span class="value">¥{{ Number((orderData?.price || 0) * (orderData?.num || 0)).toFixed(2) }}</span>
            </div>
            <div class="info-item">
              <span class="label">服务费</span>
              <span class="value">¥0.00</span>
            </div>
            <div class="info-item total-price">
              <span class="label">实付金额</span>
              <span class="value">¥{{ Number(orderData?.total || 0).toFixed(2) }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 底部操作栏 -->
      <div class="bottom-action" v-if="!loading">
        <template v-if="orderData?.status === 0">
          <van-button type="default" size="large" class="cancel-btn" @click="cancelOrder">
            取消订单
          </van-button>
          <van-button type="primary" size="large" class="pay-btn" @click="payOrder">
            立即支付
          </van-button>
        </template>
        <template v-else>
          <van-button type="primary" size="large" class="full-width-btn" @click="backToHome">
            返回首页
          </van-button>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import { api, mockData } from '../api'

export default {
  name: 'OrderDetail',
  data() {
    return {
      loading: true,
      orderData: {
        id: 0,
        user_id: 0,
        device_id: '',
        item_id: 0,
        shop_id: 0,
        num: 0,
        price: 0,
        total: 0,
        status: 0,
        create_time: 0,
        update_time: 0,
        status_text: '',
        item: {
          id: 0,
          name: '',
          image: '',
          info: ''
        },
        shop: {
          id: 0,
          shop_name: '',
          address: ''
        }
      }
    }
  },
  mounted() {
    this.getOrderDetail()
  },
  methods: {
    // 返回上一页
    goBack() {
      this.$router.back()
    },
    
    // 获取订单状态文本
    getStatusText(order) {
      // 优先使用接口返回的status_text
      if (order?.status_text) {
        return order.status_text
      }
      
      // 根据状态码显示对应的文本
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '待打酒',
        3: '出酒中',
        4: '暂停',
        5: '未完成停止',
        6: '部分退款',
        7: '全部退款',
        8: '完成'
      }
      
      return statusMap[order?.status] || '未知状态'
    },
    
    // 获取订单详情
    async getOrderDetail() {
      const orderId = this.$route.params.orderId
      if (!orderId) {
        this.$toast('订单编号错误')
        this.$router.push('/order-list')
        return
      }
      
      try {
        this.loading = true
        
        // 调用真实API获取订单详情
        const res = await api.getOrderDetail({ order_id: orderId })
       

        this.orderData = res.data
        this.loading = false
        
      } catch (error) {
        console.error('获取订单详情失败:', error)
        this.loading = false
        // 使用mock数据作为降级方案
        try {
          this.orderData = {
            ...mockData.orderDetail,
            id: orderId,
            status: 1,
            status_text: '已支付'
          }
        } catch (mockError) {
          this.$toast('获取订单详情失败')
          this.$router.push('/order-list')
        }
      }
    },
    
    // 格式化日期时间
    formatDateTime(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      switch (status) {
        case 0:
          return 'status-pending'
        case 1:
          return 'status-paid'
        case 2:
          return 'status-waiting-pour'
        case 3:
          return 'status-pouring'
        case 4:
          return 'status-paused'
        case 5:
          return 'status-stopped'
        case 6:
          return 'status-partial-refund'
        case 7:
          return 'status-full-refund'
        case 8:
          return 'status-completed'
        default:
          return ''
      }
    },
    
    // 获取状态图标
    getStatusIcon(status) {
      switch (status) {
        case 0:
          return 'clock-o'
        case 1:
          return 'success'
        case 2:
          return 'wait'
        case 3:
          return 'refresh'
        case 4:
          return 'pause-circle-o'
        case 5:
          return 'close'
        case 6:
          return 'minus-circle-o'
        case 7:
          return 'close-circle-o'
        case 8:
          return 'checked'
        default:
          return 'question'
      }
    },
    
    // 获取状态图标颜色
    getStatusIconColor(status) {
      switch (status) {
        case 0:
          return '#ff976a'
        case 1:
          return '#67c23a'
        case 2:
          return '#e6a23c'
        case 3:
          return '#409eff'
        case 4:
          return '#909399'
        case 5:
          return '#f56c6c'
        case 6:
          return '#e6a23c'
        case 7:
          return '#f56c6c'
        case 8:
          return '#67c23a'
        default:
          return '#909399'
      }
    },
    
    // 取消订单
    async cancelOrder() {
      this.$dialog.confirm({
        title: '确认取消',
        message: '您确定要取消该订单吗？',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        try {
          // 调用真实取消订单API
          await api.cancelOrder({ order_id: this.orderData.id })
          // 刷新订单详情
          await this.getOrderDetail()
          this.$toast.success('订单已取消')
        } catch (error) {
          console.error('取消订单失败:', error)
          // 模拟取消成功
          this.orderData.status = 5
          this.orderData.status_text = '未完成停止'
          this.$toast.success('订单已取消')
        }
      }).catch(() => {
        // 用户取消操作
      })
    },
    
    // 支付订单
    async payOrder() {
      try {
        this.$toast.loading({ message: '支付中...', duration: 0 })
        
        // 调用真实支付API
        await api.payOrder({ order_id: this.orderData.id })
        
        this.$toast.clear()
        // 刷新订单详情
        await this.getOrderDetail()
        this.$toast.success('支付成功')
      } catch (error) {
        this.$toast.clear()
        console.error('支付失败:', error)
        // 模拟支付成功
        this.orderData.status = 1
        this.orderData.status_text = '已支付'
        this.$toast.success('支付成功')
      }
    },
    
    // 返回首页
    backToHome() {
      this.$router.push('/')
    }
  }
}
</script>

<style scoped>
.order-detail-page {
  height: 100vh;
  background-color: #f8f8f8;
  position: relative;
}

.order-detail-container {
  width: 100%;
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 80px;
}

.header {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-icon {
  font-size: 20px;
  margin-right: 20px;
}

.header h1 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.loading {
  padding: 50px 0;
  text-align: center;
}

.content {
  padding: 0 15px 15px 15px;
}

.order-status-card {
  text-align: center;
  padding: 30px 0;
  background-color: #fff;
  margin-bottom: 10px;
}

.status-icon {
  margin-bottom: 15px;
  padding: 15px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.status-icon.status-pending {
  background-color: #fff7e6;
}

.status-icon.status-paid {
  background-color: #f0f9eb;
}

.status-icon.status-completed {
  background-color: #f0f9eb;
}

.status-icon.status-cancelled {
  background-color: #f5f5f5;
}

.order-status-card h2 {
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.valid-time {
  margin: 0;
  font-size: 14px;
  color: #f56c6c;
}

.item-card,
.order-info-card,
.shop-info-card,
.price-info-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.item-card h3,
.order-info-card h3,
.shop-info-card h3,
.price-info-card h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.item-header {
  display: flex;
  align-items: flex-start;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 15px;
}

.item-info {
  flex: 1;
}

.item-info h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.item-description {
  margin: 0 0 10px 0;
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}

.quantity {
  font-size: 14px;
  color: #666;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.label {
  color: #999;
}

.value {
  color: #333;
  font-weight: 500;
  text-align: right;
  flex: 1;
  margin-left: 15px;
}

.total-price {
  margin-top: 8px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  font-weight: bold;
  font-size: 16px;
}

.total-price .value {
  color: #f56c6c;
  font-size: 18px;
}

.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 15px;
  background-color: #fff;
  border-top: 1px solid #eee;
  z-index: 100;
  gap: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.cancel-btn,
.pay-btn,
.full-width-btn {
  flex: 1;
  padding: 12px 0;
  border-radius: 8px;
  font-size: 16px;
}

.cancel-btn {
  border: 1px solid #dcdfe6;
  color: #606266;
}

.pay-btn {
  background-color: #1989fa;
  color: #fff;
}

.full-width-btn {
  background-color: #1989fa;
  color: #fff;
}
</style>